package net.core.common;

import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

import com.handsome.ip.IPSeeker;

public class HttpUtil {
	private static final Log logger = LogFactory.getLog(HttpUtil.class);

	public static HashMap buildParameterMap(HttpServletRequest request) {
		HashMap params = new HashMap();

		if (request != null) {
			Enumeration e = request.getParameterNames();
			String key = "";
			String value = "";
			while (e.hasMoreElements()) {
				key = (String) e.nextElement();
				if (key.indexOf("[]") > 0) {
					String[] values = request.getParameterValues(key);
					String strTemp = "";
					for (int z = 0; z < values.length; z++) {
						strTemp += "," + values[z];
					}
					value = strTemp.substring(1);
				} else {
					value = (String) request.getParameter(key);
				}
				params.put(key, value);
			}
		}

		// 把session中的信息也加进来
		params = addSessionParamToMap(params, request);

		return params;
	}

	public static HashMap addSessionParamToMap(HashMap params, HttpServletRequest request) {

		try {
			if (params != null && request != null) {
				if (params.get("path") == null) {
					params.put("path", request.getContextPath());
				}

				/** 这里兼容历史版本，仍然给这些参数赋值 */
				String[] sSessionGroups = Constants.USER_SESSION_MSGGROUP.split(",");
				for (int i = 0; i < sSessionGroups.length; i++) {
					String sSessionItem = sSessionGroups[i];
					if (params.get(sSessionItem) == null) {
						params.put(sSessionItem,
								HttpUtil.getSessionAttributeStr(request, sSessionItem));
					}
				}

				/**
				 * 把session中SYS_开头的参数取出来。 add by qiuzq.2013-5-7.
				 * 放在这里写不太好，每次都要执行这段进行计算。但实际上同一个用户在session期里头是一致的。后续考虑优化
				 * 如果params参数中已经存在对应的值，则不覆盖
				 */
				HttpSession hSession = HttpUtil.getSession(request);
				if (hSession != null) {
					Enumeration<String> enSession = hSession.getAttributeNames();// 使用枚举获取这个key-value对
					while (enSession.hasMoreElements()) {
						String sSessionKey = enSession.nextElement();
						if (sSessionKey != null && sSessionKey.startsWith("SYS_")) {
							if (params.get(sSessionKey) == null) {
								params.put(sSessionKey,
										HttpUtil.getSessionAttribute(request, sSessionKey));
							}
						}
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("封装Session参数出错：", e);
		}

		return params;
	}

	public static String getSessionAttributeStr(HttpServletRequest request, String name) {
		Object object = getSessionAttribute(request, name);
		if (object != null) {
			return (String) object;
		} else {
			return "";
		}
	}

	/**
	 * Check the given request for a session attribute of the given name.
	 * Returns null if there is no session or if the session has no such
	 * attribute. Does not create a new session if none has existed before!
	 * 
	 * @param request
	 *            current HTTP request
	 * @param name
	 *            the name of the session attribute
	 * @return the value of the session attribute, or <code>null</code> if not
	 *         found
	 */
	public static Object getSessionAttribute(HttpServletRequest request, String name) {
		Assert.notNull(request, "Request must not be null");
		HttpSession session = request.getSession(false);
		return (session != null ? session.getAttribute(name) : null);
	}

	/**
	 * 返回session对象 add by qiuzq.2013-5-7
	 * 
	 * @param request
	 * @return
	 */
	public static HttpSession getSession(HttpServletRequest request) {
		return request.getSession(false);
	}

	/**
	 * 获取当前登陆用户的姓名
	 * 
	 * @Title: getCurrentLoginUserName
	 * @param request
	 * @return
	 * @return String
	 * @description
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-8-5 上午09:26:19
	 */
	public static String getCurrentLoginUserName(HttpServletRequest request) {
		Object object = getSessionAttribute(request, "userName");
		if (object != null) {
			return (String) object;
		} else {
			return "";
		}
	}

	/**
	 * 获取当前登陆用户的ID
	 * 
	 * @Title: getCurrentLoginUserId
	 * @param request
	 * @return
	 * @return String
	 * @description
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-8-5 上午09:26:13
	 */
	public static String getCurrentLoginUserId(HttpServletRequest request) {
		Object object = getSessionAttribute(request, "userId");
		if (object != null) {
			return (String) object;
		} else {
			return "guest";
		}
	}

	/**
	 * 获取当前登陆用户的区域编码
	 * 
	 * @Title: getCurrentLoginUserAreaCode
	 * @param request
	 * @return
	 * @return String
	 * @description
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-8-5 上午09:36:05
	 */
	public static String getCurrentLoginUserAreaCode(HttpServletRequest request) {
		Object object = getSessionAttribute(request, "areaCode");
		if (object != null) {
			return (String) object;
		} else {
			return "";
		}
	}

	/**
	 * 
	 * Description: 获得客户端访问ip地址
	 * 
	 * @Title: getIpAddr
	 * @param request
	 * @return String
	 * @author zyfine
	 * @date Jan 13, 2010
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String iplist[] = ip.split(",");
		ip = iplist[0];
		return ip;
	}

	/**
	 * 
	 * Description: 获得客户端访问ip地址 所在区域
	 * 
	 * @Title: getIpArea
	 * @param ipAddr
	 * @return String
	 * @author shenlw
	 */
	public static String getIpArea(String ipAddr, String dir) {
		String address = "";
		try {
			// 指定纯真数据库的文件名，所在文件夹
			IPSeeker ip = new IPSeeker("IPAREA.Dat", dir);
			// 获得地区
			address = ip.getIPLocation(ipAddr).getCountry();
			// System.out.println(address);
		} catch (Exception e) {
			e.printStackTrace();
			return ipAddr;
		}
		return address;
	}

	/**
	 * 
	 * Description: 获得客户端访问ip地址 类型（:网通电信等）
	 * 
	 * @Title: getIpType
	 * @param ipAddr
	 * @return String
	 * @author shenlw
	 */
	public static String getIpType(String ipAddr, String dir) {
		// 指定纯真数据库的文件名，所在文件夹
		IPSeeker ip = new IPSeeker("IPAREA.Dat", dir);
		// 获得类型:网通电信等
		String type = ip.getIPLocation(ipAddr).getArea();
		// System.out.println(type);
		return type;
	}

	public static void main(String[] args) {
		System.out.println(getIpArea("222.128.61.110",
				"E:/Workspaces/sunnada/mini_zb/web/WEB-INF/classes/ip"));
		System.out.println(getIpType("222.128.61.110",
				"E:/Workspaces/sunnada/mini_zb/web/WEB-INF/classes/ip"));
	}

}
